/**
 * 首页模块
 * 默认模块名: flPage
 * @return {[object]}  [ 返回一个对象 ]
 */
let storage = bui.storage();
let ggArrr = []
let timer;
let language;
let translate;

let ROLL_SPEED = 150
let noticeList1;
let noticeList2;
let listWrapper;
let noticeTimer;

let shareImage;
let ids

loader.define(function(require, exports, module, global) {
    let pageview = {};

    // 模块初始化定义
    pageview.init = function() {
        translate = global.translate
        language = storage.get("language", 0)
        if (!language) {
            language = 'chinese_simplified'
        }

        try {
            translate.selectLanguageTag.show = false;
            translate.ignore.id.push('languageContent')
            let curLanguage = translate.language.getCurrent()
            if (curLanguage !== language) {
                translate.changeLanguage(language)
            }
            translate.execute();
        }catch (e) {
            console.log("切换语言报错")
        }
        let languageArr = storage.get('languageArr',0)
        let html = ''
        let html2 = '<select class="languageSelect" id="languageSelectId">\n'
        if (language !== 'chinese_simplified' && language !== 'english') {
            languageArr.forEach(lan => {
                if (lan.id === language) {
                    html += '<span class="language" id="'+lan.id+'">'+lan.name+'</span>|'
                } else {
                    html2 += '<option value="'+lan.id+'">'+lan.name+'</option>'
                }
            })
        } else {
            languageArr.forEach(lan => {
                html2 += '<option value="'+lan.id+'">'+lan.name+'</option>'
            })
        }
        html+= '<span class="language" id="english">English</span>|<span class="language" id="chinese_simplified">简体中文</span>'
        router.$("#languageContent").html(html + html2 + "</select>")
        router.$("#languageSelectId").val('')

        router.$(".language").click(function () {
            let selectId = $(this).attr('id')
            if (selectId !== language) {
                storage.set("language", selectId)
                location.reload()
            }
        })
        router.$("#languageSelectId").change(function () {
            let selectId = $(this).val()
            if (selectId !== language) {
                storage.set("language", selectId)
                location.reload()
            }
        })

        let uiLoading = bui.loading({
            appendTo:"#flPageLoading",
            width: 40,
            height: 40,
            opacity: 0.5,
            text:"加载中。。。",
            autoClose: false
        });

        // uiLoading.show()

        // router.$("#flPageFh").click(function () {
        //     // let params = module.props;
        //     // if (params.tzSign === '0') {
        //     //     storage.set("tzPage", 0)
        //     //     router.replace({url: "pages/mainIndex/mainIndex.html"});
        //     // } else if (params.tzSign === '1') {
        //     //     let article = storage.get("tzArticleInfo",0)
        //     //     router.load({ url: "pages/articleInfo/articleInfo.html", param: {tzSign: '0',id: article.id, glUserid: article.glUserid}});
        //     // } else {
        //     //     router.load({ url: "pages/typePage/typePage.html"});
        //     // }
        //     bui.back()
        // })

        let org = storage.get("org",0)
        const url = window.location.href
        let cdCate,menCate;
        if (url.indexOf("?") > -1) {
            let param = url.split("?")[1].split("&")[0]
            cdCate = param.split("=")[1]
            menCate = cdCate.split('-')

            let care = menCate[0]
            if (!care || care === 'null' || care === 'undefined'){
                care = ''
            } else {
                bui.ajax({
                    url: global.api.getCityById,
                    data: {id: care},
                    method: "POST"
                }).then(function(res){
                    let data = res.data
                    if (data.shareImage) {
                        shareImage = data.shareImage
                    } else {
                        shareImage = 'http://58hw.oss-cn-beijing.aliyuncs.com/58Upload/term/flpage.jpg'
                    }
                })
            }

            bui.ajax({
                url: global.api.getCityById,
                data: {id: menCate[2]},
                method: "POST"
            }).then(function(res){
                org = res.data
                storage.set("org", res.data)

                bui.ajax({
                    url: global.api.getTypeMenuList,
                    data: {city: org.id, id: menCate[0]},
                    method: "POST"
                }).then(function(res){
                    let data = res.data
                    let html = ''
                    data.forEach((term,index) => {
                        if (index % 4 === 0) {
                            if (index !== 0) {
                                html += '</div>' +
                                    '</div>'
                            }
                            html += '<div class="span1" style="margin-bottom: 20px">'+
                                '<div class="bui-box">'
                        }
                        html += '<div class="span1 cate" id="'+term.id+'" name="'+term.name+'"><div class="typeYs">'+term.name+'</div></div>'
                    })
                    html += '</div>' +
                        '</div>'
                    router.$("#typeXx").html(html)

                    router.$('.cate').click(function () {
                        router.replace({ url: "pages/flPage/flPage.html", param:{menCate: router.$(this).attr('id') + '-' + router.$(this).attr('name') + "-" + org.id}});
                    })
                })

                selectList(org,care,decodeURIComponent(menCate[1]),global,cdCate,uiLoading)
            })

            router.$("#flPageFh").click(function () {
                storage.set("tzPage", 0)
                router.replace({url: "pages/mainIndex/mainIndex.html"});
            })
        } else {
            cdCate = storage.get("menCate",0)
            menCate = cdCate.split('-')

            let care = menCate[0]
            if (!care || care === 'null' || care === 'undefined'){
                care = ''
            } else {
                bui.ajax({
                    url: global.api.getCityById,
                    data: {id: care},
                    method: "POST"
                }).then(function(res){
                    let data = res.data
                    if (data.shareImage) {
                        shareImage = data.shareImage
                    } else {
                        shareImage = 'http://58hw.oss-cn-beijing.aliyuncs.com/58Upload/term/flpage.jpg'
                    }
                })
            }

            router.$("#flPageFh").click(function () {
                let prevInfo = bui.history.getCurrentPrev()
                router.replace({url: prevInfo.url});
            })

            if (org){
                bui.ajax({
                    url: global.api.getTypeMenuList,
                    data: {city: org.id, id: menCate[0]},
                    method: "POST"
                }).then(function(res){
                    let data = res.data
                    let html = ''
                    data.forEach((term,index) => {
                        if (index % 4 === 0) {
                            if (index !== 0) {
                                html += '</div>' +
                                    '</div>'
                            }
                            html += '<div class="span1" style="margin-bottom: 20px">'+
                                '<div class="bui-box">'
                        }
                        html += '<div class="span1 cate" id="'+term.id+'" name="'+term.name+'"><div class="typeYs">'+term.name+'</div></div>'
                    })
                    html += '</div>' +
                        '</div>'
                    router.$("#typeXx").html(html)

                    router.$('.cate').click(function () {
                        storage.set('menCate', router.$(this).attr('id') + '-' + router.$(this).attr('name') + "-" + org.id)
                        router.replace({ url: "pages/flPage/flPage.html"});
                    })
                })

                selectList(org,care,decodeURIComponent(menCate[1]),global,cdCate,uiLoading)
            }
        }

        router.$("#mainPage").click(function () {
            storage.set("tzPage", 0)
            router.replace({url: "pages/mainIndex/mainIndex.html"});
        })
        router.$("#moreCate").click(function () {
            router.load({ url: "pages/typePage/typePage.html"});
        })

        let cateStr = decodeURIComponent(menCate[1])
        router.$("#topCate").html(cateStr)
        ggArrr = []
        router.$("#typeTitle").html(org.description+ cateStr)

        router.$("#advertiseType").click(function () {
            let param = router.$(this).attr("name")
            let params = param.split('~')
            let id = params[0]
            let glUserid = params[1]
            router.load({ url: "pages/articleInfo/articleInfo.html", param: {id: id, glUserid: glUserid}});
            // storage.set("article", param)
            // bui.load({ url: "pages/home/index.html"});
        })
    }

    // 初始化
    pageview.init();

    // 输出模块
    return pageview;
})

function formatDate(time) {
    let date = new Date(time * 1000);
    let Y = date.getFullYear() + '-';
    let M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
    let D = (date.getDate() < 10 ? '0'+(date.getDate()) : date.getDate()) + ' ';
    let h = (date.getHours() < 10 ? '0'+(date.getHours()) : date.getHours()) + ':';
    let m = (date.getMinutes() < 10 ? '0'+(date.getMinutes()) : date.getMinutes()) + ':';
    let s = (date.getSeconds() < 10 ? '0'+(date.getSeconds()) : date.getSeconds());
    return Y+M+D+h+m+s
}

function isMobile() {
    let userAgentInfo = navigator.userAgent;

    let mobileAgents = ["Android", "iPhone", "SymbianOS", "Windows Phone", "iPad", "iPod"];

    let mobile_flag = false;

    let ua = navigator.userAgent.toLowerCase()
    if (ua.match(/MicroMessenger/i) == "micromessenger") {
        mobile_flag = true
    } else {
        //根据userAgent判断是否是手机
        for (let v = 0; v < mobileAgents.length; v++) {
            if (userAgentInfo.indexOf(mobileAgents[v]) > 0) {
                mobile_flag = true;
                break;
            }
        }
    }

    return mobile_flag;
}

function isWeiXin() {
    let ua = navigator.userAgent.toLowerCase()
    if (ua.match(/MicroMessenger/i) == "micromessenger") {
        return true
    } else {
        return false
    }
}

function selectList(org,care, cateStr, global,cdCate,uiLoading) {
    ids = []
    let share = {
        title: '',
        description: ''
    }

    let  list = bui.list({
        id: "#scrollList2",
        uid: 'flPageScrollList',
        url: global.api.getArticleList,
        pageSize: 10, // 当pageSize 小于返回的数据大小的时候,则认为是最后一页,接口返回的数据最好能返回空数组,而不是null
        data: {
            city: org.id,
            redisCity: org.name,
            country: org.parent,
            'isfix1': '1',
            isduplicate: 0,
            cate: care
        },
        //如果分页的字段名不一样,通过field重新定义
        field: {
            page: "page",
            size: "limit",
            data: "data"
        },
        callback: function(e) {
            // e.target 为你当前点击的元素
            // e.currentTarget 为你当前点击的handle 整行
            let id = router.$(e.currentTarget).attr("id")
            let glUserid = router.$(e.currentTarget).attr("name")
            router.load({ url: "pages/articleInfo/articleInfo.html", param: {id: id, glUserid: glUserid}});
        },
        template: function(data) {
            var html = "";

            let picClass = 'imgBJPC'
            if (isMobile()) {
                picClass = 'imgBJ'
            }

            let fontSize = '0.3rem'
            let fontSize2 = '0.24rem'
            let fontSize3 = '0.2rem'
            if (language !== "chinese_simplified") {
                fontSize = '0.22rem'
                fontSize2 = '0.18rem'
                fontSize3 = '0.12rem'
            }

            if (!share.title && data.length > 0){
                let first = data[0]
                share.title = first.title
                let contentText = ""
                if (first.contentText){
                    contentText = first.contentText.replace(/[\r\n]/g,"").substring(0,50)
                }
                share.description = contentText

                if (isWeiXin()) {
                    //获取微信配置
                    bui.ajax({
                        url: global.api.getWxConfig,
                        data: {url: location.href.split('#')[0]},
                        method: "GET"
                    }).then(function(res){
                        if (res.code == '200') {
                            let dat = res.data

                            wx.config({
                                debug: false,
                                appId: dat.appId,
                                timestamp: dat.timestamp,
                                nonceStr: dat.nonceStr,
                                signature: dat.signature,
                                jsApiList: ["updateTimelineShareData", "updateAppMessageShareData", "onMenuShareTimeline", "onMenuShareAppMessage"]
                            })
                            wx.ready(function () {   //需在用户可能点击分享按钮前就先调用
                                wx.onMenuShareAppMessage({
                                    title: '【'+cateStr+'】' + share.title, // 分享标题
                                    desc: share.description, // 分享描述
                                    link: 'https://ty.happindo.com/#pages/flPage/flPage?cdCate='+ encodeURIComponent(cdCate) + "&nonce=" + translate.generateRandomString(4), // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                                    imgUrl: shareImage, // 分享图标
                                    type: '', // 分享类型,music、video或link，不填默认为link
                                    dataUrl: '',
                                    success: function () {
                                    }
                                })
                                wx.onMenuShareTimeline({
                                    title: '【'+cateStr+'】' + share.title, // 分享标题
                                    desc: share.description, // 分享描述
                                    link: 'https://ty.happindo.com/#pages/flPage/flPage?cdCate='+encodeURIComponent(cdCate) + "&nonce=" + translate.generateRandomString(4), // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                                    imgUrl: shareImage, // 分享图标
                                    success: function () {
                                    }
                                })
                            });
                        } else {
                            // bui.alert(res.msg)
                        }
                    })
                }
            }

            let newIds = []
            data.forEach(function(el, index) {
                if (ids.indexOf(el.id) === -1) {
                    newIds.push(el.id)
                    html += '<li class="bui-btn bui-box-vertical" id="'+el.id+'" name="'+el.glUserid+'">\n' +
                        '                            <div style="min-height: 60px">\n'
                    if (el.zd == '0') {
                        html += '                                <div class="zdK" style="font-size: '+fontSize+'">荐</div><p style="color: black;font-size: '+fontSize+';margin-bottom: 0.22rem">'+el.title+'</p>\n'
                    } else {
                        html += '                                <p style="color: black;font-size: '+fontSize+';margin-bottom: 0.22rem">'+el.title+'</p>\n'
                    }

                    if (el.contentText) {
                        if (el.contentText) {
                            html += '                        <p style="color: rgb(120,120,120);font-size: '+fontSize3+';margin-bottom: 0.22rem">'+el.contentText.substring(0,100)
                            if(el.contentText.length > 100) {
                                html += '...'
                            }
                            html += '</p>\n'
                        }
                    }
                    html += '                                <p class="item-text">\n' +
                        '                                    <span class="listTab" style="font-size: '+fontSize2+'">'+el.cateStr+'</span>\n' +
                        '                                    <span style="font-size: '+fontSize2+'">\n' + formatDate(el.ptime) + '</span>\n' +
                        '                                    <span style="font-size: '+fontSize2+'">'+org.description+'</span>\n' +
                        '                                </p>\n' +
                        '                            </div>\n'+
                        '                            <div class="span1">\n'+
                        '                                <div class="bui-box">\n'

                    if (el.imgs && el.imgs.length > 0) {
                        let len = el.imgs.length > 3 ? 3 : el.imgs.length
                        for (let i = 0; i < len; i++) {
                            html +=  '                                    <div class="span1 '+picClass+'">\n' +
                                '                                        <img src="'+el.imgs[i]+'?x-oss-process=style/index" alt="">\n' +
                                '                                    </div>\n'
                        }

                        if (len < 3) {
                            for (let i = 0; i < 3- len; i++) {
                                html +=  '                                    <div class="span1 '+picClass+'">\n' +
                                    '                                    </div>\n'
                            }
                        }

                        html += '                                </div>\n' +
                            '                            </div>\n' +
                            '                        </li>'
                    } else {
                        html += '                        </li>'
                    }
                }
            });

            if (!html) {
                data.forEach(function(el, index) {
                    newIds.push(el.id)
                    html += '<li class="bui-btn bui-box-vertical" id="'+el.id+'" name="'+el.glUserid+'">\n' +
                        '                            <div style="min-height: 60px">\n'
                    if (el.zd == '0') {
                        html += '                                <div class="zdK" style="font-size: '+fontSize+'">荐</div><p style="color: black;font-size: '+fontSize+';margin-bottom: 0.22rem">'+el.title+'</p>\n'
                    } else {
                        html += '                                <p style="color: black;font-size: '+fontSize+';margin-bottom: 0.22rem">'+el.title+'</p>\n'
                    }

                    if (el.contentText) {
                        if (el.contentText) {
                            html += '                        <p style="color: rgb(120,120,120);font-size: '+fontSize3+';margin-bottom: 0.22rem">'+el.contentText.substring(0,100)
                            if(el.contentText.length > 100) {
                                html += '...'
                            }
                            html += '</p>\n'
                        }
                    }
                    html += '                                <p class="item-text">\n' +
                        '                                    <span class="listTab" style="font-size: '+fontSize2+'">'+el.cateStr+'</span>\n' +
                        '                                    <span style="font-size: '+fontSize2+'">\n' + formatDate(el.ptime) + '</span>\n' +
                        '                                    <span style="font-size: '+fontSize2+'">'+org.description+'</span>\n' +
                        '                                </p>\n' +
                        '                            </div>\n'+
                        '                            <div class="span1">\n'+
                        '                                <div class="bui-box">\n'

                    if (el.imgs && el.imgs.length > 0) {
                        let len = el.imgs.length > 3 ? 3 : el.imgs.length
                        for (let i = 0; i < len; i++) {
                            html +=  '                                    <div class="span1 '+picClass+'">\n' +
                                '                                        <img src="'+el.imgs[i]+'?x-oss-process=style/index" alt="">\n' +
                                '                                    </div>\n'
                        }

                        if (len < 3) {
                            for (let i = 0; i < 3- len; i++) {
                                html +=  '                                    <div class="span1 '+picClass+'">\n' +
                                    '                                    </div>\n'
                            }
                        }

                        html += '                                </div>\n' +
                            '                            </div>\n' +
                            '                        </li>'
                    } else {
                        html += '                        </li>'
                    }
                });
            }

            ids = newIds
            uiLoading.stop()
            setTimeout(function () {
                try {
                    translate.execute();
                }catch (e) {
                    console.log("切换语言报错")
                }
            },1000)

            return html;
        }
    })

    //加载广告
    bui.ajax({
        url: global.api.getAdvertiseList,
        data: {city: org.id, redisCity: org.name,country: org.parent, place: '2'},
        method: "POST"
    }).then(function(res){
        ggArrr = res.data
        router.$("#advertiseType").hide()
        if (ggArrr && ggArrr.length > 0) {
            let index = Math.floor(Math.random()*ggArrr.length)
            router.$("#advertiseType").attr("src", ggArrr[index].imgUrl)
            router.$("#advertiseType").attr("name", ggArrr[index].article + '~' + ggArrr[index].title)
            router.$("#advertiseType").show()
        }
    })
}
